<?php
namespace app\api\controller;
use app\admin\model\VerifyCode as VerifyCodeMode;
use think\Controller;

class ApiBaseController extends Controller {
	
	protected function _initialize() {
		parent::_initialize();
		header('Access-Control-Allow-Origin:*');
		//验证key,是否非法访问
	}

	/**
	 * 通用code代码
	 * 200 请求成功
	 * 400 请求非法、密钥错误
	 * 401 请求方式错误
	 * 402 参数为空、格式错误
	 * 403 服务器内部错误
	 * 404 找不到API方法
	 * 405 返回数据为空
	 * 406 数据库错误
	 * 407 PHP错误
	 * 408 业务逻辑错误
	 * 409 自定义错误
	 */
	protected function toJson($code='', $msg='', $data='') {
		return json(['code'=>$code,'msg'=>$msg,'data'=>$data]);
	}
	
	protected function uploadOne() {
		$data = $this->request->post();
		return $this->toJson(200,'',$data);
	}
	
	
	
	  /**
      * @desc 根据两点间的经纬度计算距离
      * @param float $lat 纬度值
      * @param float $lng 经度值
      */
      function get_distance($lat1,$lng1,$lat2,$lng2){
        $earthRadius = 6367000; //approximate radius of earth in meters

        $lat1 = ($lat1 * pi() ) / 180;
        $lng1 = ($lng1 * pi() ) / 180;

        $lat2 = ($lat2 * pi() ) / 180;
        $lng2 = ($lng2 * pi() ) / 180;

        $calcLongitude = $lng2 - $lng1;
        $calcLatitude = $lat2 - $lat1;
        $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
        $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
        $calculatedDistance = $earthRadius * $stepTwo;

        return round($calculatedDistance);
      }

	protected function upload($path) {
		if ($this->request->isPost()) {
			$ret = array('strings' => $_POST, 'error' => '0');
			$fs = array();
			foreach ($_FILES as $name => $file) {
				$fn = $file['name'];
				$ft = strrpos($fn, '.', 0);
				$fm = substr($fn, 0, $ft);
				$fe = substr($fn, $ft);
				$fn = time()."_".rand(100000, 999999) . $fe;
				$fp = './public/uploads/' . $path .'/'. $fn;
				//move_uploaded_file($file['tmp_name'], $fp);
				$image = \image\Image::open($file['tmp_name']);
				$image->thumb(100, 100)->save($fp);
				$fs[$name] = array('name' => $fn, 'url' => $fp, 'type' => $file['type'], 'size' => $file['size']);
			}
			$ret['files'] = $fs;
			echo json_encode($ret);
		} else {
			echo "{'error':'不支持 GET请求!'}";
		}
	}
	protected function crop_img($file,$path){
		$image = \think\Image::open($file);
		$image->crop(100, 100)->save($path);
		$size = $image->size(); 
	}
	protected function check_code($mobile, $code, $message){
		$code_model =  new VerifyCodeMode();
		$where['mobile'] = $mobile;
		$where['message'] = $message;
		$where['result'] = '发送成功';
		$result = $code_model -> where($where) -> order('add_time desc')-> find();
		// 10分钟有效期
		if(time() - strtotime($result['add_time']) > 600){
			return 2;
		}
		if($code == $result['code']){
			return 1;
		}else{
			return -1;
		}
	}

}
